/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
/**
 * @desc 用户相关业务
 * @fileName user.ts
 * @author zoujunjie@yzbdl.ac.cn
 * @date 2022-4-28
 */
import http from "./common/http";
import localTokenStrategy from "@/common/util/auth";
import { clearMenuPermissionsCache } from "./user-permission";
import { encryptAes } from "./common/tool";

interface ChangePasswordModel {
  old: string; //旧密码
  new: string; //新密码
  confirm: string; //确认密码
}

/**
 * 修改密码
 */
const changePassword = async (
  data: ChangePasswordModel,
  isAdminRoute: boolean
) => {
  return new Promise((resolve, reject) => {
    if (isAdminRoute) {
      http
        .post({
          url: "/manager/password",
          data: {
            newPassword: encryptAes(data.new),
            oldPassword: encryptAes(data.old),
          },
        })
        .then((r) => {
          resolve(r);
        })
        .catch((err) => {
          reject(err);
        });
    } else {
      http
        .post({
          url: "/personal/password",
          data: {
            newPassword: encryptAes(data.new),
            oldPassword: encryptAes(data.old),
          },
        })
        .then((r) => {
          resolve(r);
        })
        .catch((err) => {
          reject(err);
        });
    }
  });
};

/**
 * 获取用户的所有组织
 * @returns 组织列表
 */
const getAllOrganizations = async () => {
  return new Promise((resolve, reject) => {
    http
      .get({
        url: "/personal/org",
      })
      .then((r: any) => {
        resolve(r.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

const changeOrganization = async (organizationId: string) => {
  return new Promise((resolve, reject) => {
    if (Number(organizationId) > 0) {
      http
        .get({
          url: `/personal/org/change/${organizationId}`,
        })
        .then((r: any) => {
          resolve(r.data);
        })
        .catch((err) => {
          reject(err);
        });
    } else {
      reject("参数错误");
    }
  });
};

const getCurrentUser = () => {
  return localTokenStrategy.getUserInfo();
};

const logout = () => {
  localTokenStrategy.setToken(null);
  localTokenStrategy.setUserInfo(null);
  clearMenuPermissionsCache();
};

export {
  ChangePasswordModel,
  changePassword,
  getAllOrganizations,
  changeOrganization,
  getCurrentUser,
  logout,
};
